<template>
  <div class="tencent-map-container">
    <div class="map-header">
      <h3>腾讯地图选点</h3>
      <div class="coordinates-display" v-if="selectedCoordinates">
        <span class="coord-label">经度:</span>
        <span class="coord-value">{{ selectedCoordinates.lng }}</span>
        <span class="coord-label">纬度:</span>
        <span class="coord-value">{{ selectedCoordinates.lat }}</span>
        <el-button size="small" type="primary" @click="confirmSelection">确认选择</el-button>
        <el-button size="small" @click="clearSelection">清除</el-button>
      </div>
    </div>
    <div 
      ref="mapContainer" 
      class="map-container"
      :style="{ width: mapWidth, height: mapHeight }"
    ></div>
    <div class="map-footer" v-if="showFooter">
      <p class="tip-text">点击地图任意位置获取经纬度坐标</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'

// 定义组件属性
interface Props {
  width?: string
  height?: string
  center?: { lat: number; lng: number }
  zoom?: number
  showFooter?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  height: '400px',
  center: () => ({ lat: 39.908823, lng: 116.397470 }), // 默认北京天安门
  zoom: 12,
  showFooter: true,
})

// 定义事件
interface Emits {
  (e: 'coordinate-selected', coordinates: { lat: number; lng: number }): void
  (e: 'map-ready'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const mapContainer = ref<HTMLElement>()
const selectedCoordinates = ref<{ lat: number; lng: number } | null>(null)
const mapInstance = ref<any>(null)
const marker = ref<any>(null)

// 计算属性
const mapWidth = ref(props.width)
const mapHeight = ref(props.height)

// 加载腾讯地图API
const loadTencentMapAPI = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (window.qq && window.qq.maps) {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.src = `https://map.qq.com/api/gljs?v=1.exp&key=SGLBZ-VUZ63-A4I3L-OF6HW-YQXNZ-SPFEI&callback=initTencentMap`
    script.async = true
    script.onerror = () => reject(new Error('腾讯地图API加载失败'))
    
    // 全局回调函数
    window.initTencentMap = () => {
      resolve()
    }
    
    document.head.appendChild(script)
  })
}

// 初始化地图
const initMap = async () => {
  try {
    await loadTencentMapAPI()
    
    if (!mapContainer.value) return

    // 创建地图实例
    mapInstance.value = new window.qq.maps.Map(mapContainer.value, {
      center: new window.qq.maps.LatLng(props.center.lat, props.center.lng),
      zoom: props.zoom,
      mapTypeId: window.qq.maps.MapTypeId.ROADMAP
    })

    // 添加点击事件监听
    window.qq.maps.event.addListener(mapInstance.value, 'click', (event: any) => {
      const lat = event.latLng.getLat()
      const lng = event.latLng.getLng()
      
      // 更新选中的坐标
      selectedCoordinates.value = { lat, lng }
      
      // 清除之前的标记
      if (marker.value) {
        marker.value.setMap(null)
      }
      
      // 添加新标记
      marker.value = new window.qq.maps.Marker({
        position: event.latLng,
        map: mapInstance.value,
        title: `经度: ${lng.toFixed(6)}, 纬度: ${lat.toFixed(6)}`
      })
      
      // 触发事件
      emit('coordinate-selected', { lat, lng })
      
      ElMessage.success(`已选择坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`)
    })

    emit('map-ready')
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败，请检查网络连接或API Key')
  }
}

// 确认选择
const confirmSelection = () => {
  if (selectedCoordinates.value) {
    ElMessage.success('坐标选择已确认')
    // 可以在这里添加额外的确认逻辑
  }
}

// 清除选择
const clearSelection = () => {
  selectedCoordinates.value = null
  if (marker.value) {
    marker.value.setMap(null)
    marker.value = null
  }
  ElMessage.info('已清除选择')
}

// 设置地图中心点
const setCenter = (lat: number, lng: number) => {
  if (mapInstance.value) {
    const center = new window.qq.maps.LatLng(lat, lng)
    mapInstance.value.setCenter(center)
  }
}

// 设置地图缩放级别
const setZoom = (zoom: number) => {
  if (mapInstance.value) {
    mapInstance.value.setZoom(zoom)
  }
}

// 获取当前选中的坐标
const getSelectedCoordinates = () => {
  return selectedCoordinates.value
}

// 暴露方法给父组件
defineExpose({
  setCenter,
  setZoom,
  getSelectedCoordinates,
  clearSelection
})

// 监听中心点变化
watch(() => props.center, (newCenter) => {
  if (mapInstance.value && newCenter) {
    setCenter(newCenter.lat, newCenter.lng)
  }
}, { deep: true })

// 监听缩放级别变化
watch(() => props.zoom, (newZoom) => {
  if (mapInstance.value && newZoom) {
    setZoom(newZoom)
  }
})

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})

// 组件卸载时清理
onUnmounted(() => {
  if (marker.value) {
    marker.value.setMap(null)
  }
  if (mapInstance.value) {
    // 清理地图实例
    mapInstance.value = null
  }
})

// 声明全局类型
declare global {
  interface Window {
    qq: any
    initTencentMap: () => void
  }
}
</script>

<style scoped>
.tencent-map-container {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
}

.map-header {
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.map-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.coordinates-display {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.coord-label {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.coord-value {
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 4px;
  min-width: 80px;
  text-align: center;
}

.map-container {
  position: relative;
  background: #f0f0f0;
}

.map-footer {
  padding: 12px 16px;
  background: #f9fafc;
  border-top: 1px solid #ebeef5;
}

.tip-text {
  margin: 0;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .coordinates-display {
    width: 100%;
    justify-content: flex-start;
  }
  
  .coord-value {
    min-width: 70px;
  }
}
</style>